<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Guestbook as GuestbookModel;
use app\common\validate\GuestbookValidate;
use think\facade\Cache;
use think\captcha\Captcha;
class Guestbook extends Common {
	//首页
	public function index(){
		// 获取配置项
		// p($this->config);die;
		$data = request()->param();
		return $this->fetch();
	}
	//留言列表
	public function index_lists(){
		$limit = request()->param('limit');
		$page = request()->param('page');
		$start = ($page-1)*$limit;
		$count = db('guestbook')->count();
		$result = db('guestbook')
					->limit($start,$limit)
					->order('id desc,listorder desc')
					->cache('guestbook'.$limit.$page,3600,'guestbook')
					->select();
		
		return showTable(0, 'OK', $count ,$result, 200);
		
	}
	//在线留言添加
	public function add(){
		if(request()->isPost()){
			$data = request()->param();
			if(config('template.captcha')){
				$captcha = new Captcha();
				if(!$captcha->check($data['captcha']))
				{
					return show(0, "验证码错误", 0 , 200);
				}
			}
			$data['inputtime'] = time();		
			$validate = new GuestbookValidate;
			if (!$validate->scene('add')->check($data)) {
				return show(0, $validate->getError(), 0 , 200);
			}else{
				Cache::clear('guestbook');
				$rest = (new GuestbookModel())->strict(false)->insert($data);
				return show(1, '添加成功', $rest, 200);
			}			
		}
		return $this->fetch();
	}
	
	//在线留言删除
	public function dele(){
		$data = request()->param();
		$result = db('guestbook')->delete($data['id']);
		Cache::clear('guestbook');
		return show(1, '删除成功', $result, 200);
	}
	//在线留言全删
	public function all_dele(){
		$data = request()->param();
		$result = db('guestbook')->delete($data['ids']);
		Cache::clear('guestbook');
		return show(1, '删除成功', $result, 200);
	}
	//查看留言
	public function show_content(){
		$data = request()->param();
		$result = db('guestbook')->find($data['id']);
		return show(1, '查看留言', $result, 200);
	}
	//友情链接排序
	public function sort(){
		$data = request()->param();
		
		$validate = new GuestbookValidate;
		
		if (!$validate->scene('sort')->check($data)) {
			return show(config('code.error'), 'error', $validate->getError(), 200);
		}else{
			Cache::clear('guestbook');
			$rest = (new GuestbookModel())->save(['listorder'=>$data['listorder']],['id'=>$data['id']]);
			return show(config('code.success'), 'OK', $rest, 200);
		}
			
	}
	//在线留言回复列表
	public function reply(){
		$data = request()->param();
		$count = db('guestbook')->where('id',$data['id'])->count();
		$result = db('reply')->where('id',$data['id'])->select();
		return showTable(0, 'OK', $count ,$result, 200);
	}
	
	//在线留言是否显示
	public function is_check(){
		$data = request()->param();
		Cache::clear('guestbook');
		$result = db('guestbook')->where('id',$data['id'])->update(['status'=>$data['status']]);
		return show(1, '设置成功', $result, 200);
	}
}
